package com.cherry.androidcode.activity

import android.app.Activity
import android.content.ContentUris
import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.cherry.androidcode.R
import com.cherry.androidcode.image.GlideApp
import kotlinx.android.synthetic.main.activity_android_q.*
import java.io.*
import kotlin.concurrent.thread


/**
 * @author DongMS
 * @since 2020-10-15
 */
class AndroidQActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_android_q)
    }

    /////存储访问框架SAF/////
    //获取系统中的文件，使用系统自带的选择器
    fun queryFileSAF(view: View) {
        //通过系统的文件浏览器选择一个文件
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        //筛选，只显示可以“打开”的结果，如文件(而不是联系人或时区列表)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "*/*"
        startActivityForResult(intent, REQUEST_CODE_FOR_SINGLE_FILE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_FOR_SINGLE_FILE -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    val uri = data.data
                    if (uri != null) {

                        // 获取文件信息
                        val fileArray = arrayOf(MediaStore.Files.FileColumns.DISPLAY_NAME, MediaStore.Files.FileColumns.SIZE, MediaStore.Files.FileColumns.MIME_TYPE)
                        val cursor = this.contentResolver
                                .query(uri, fileArray, null, null, null, null)
                        if (cursor != null && cursor.moveToFirst()) {
                            val displayName = cursor.getString(cursor.getColumnIndexOrThrow(fileArray[0]))
                            val size = cursor.getString(cursor.getColumnIndexOrThrow(fileArray[1]))
                            val mimeType = cursor.getString(cursor.getColumnIndexOrThrow(fileArray[2]))
                            Log.w("-----", "Name: $displayName")
                            Log.w("-----", "Size: $size")
                            Log.w("-----", "mimeType: $mimeType")
                        }
                        cursor?.close()

//                        val inputStream = contentResolver.openInputStream(uri)
//                        // 执行文件读取操作
//                        //retrofit 上传文件
//                        Log.w("-----", uri.toString())
//                        val mimeType = contentResolver.getType(uri)
//
//                        Log.w("-----", mimeType)
//                        val requestBody = RequestBody.create(MediaType.parse(mimeType), inputStream?.readBytes())
                    }
                }
            }
            REQUEST_CODE_FOR_DELETE_FILE -> deleteFileSAF(data?.data)

        }
    }

    /**
     * 创建文件
     */
    fun createFileSAF(view: View) {
        val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        // 文件类型
        intent.type = "text/plain"
        // 文件名称
        intent.putExtra(Intent.EXTRA_TITLE, System.currentTimeMillis().toString() + ".txt")
        startActivityForResult(intent, REQUEST_CODE_FOR_WRITE_FILE)
    }

    /**
     * 删除文件，不常用
     */
    fun deleteFileSAF(view: View) {
        //通过系统的文件浏览器选择一个文件
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        //筛选，只显示可以“打开”的结果，如文件(而不是联系人或时区列表)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "*/*"
        startActivityForResult(intent, REQUEST_CODE_FOR_DELETE_FILE)
    }

    private fun deleteFileSAF(uri: Uri?) {
        if (uri != null) {
            try {
                DocumentsContract.deleteDocument(contentResolver, uri)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
        }
    }


    //////////MediaStore//////////


    //获取相册中的图片，返回uri,无法获取文件Uri
    fun queryImageUri(view: View) {
        val cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, "${MediaStore.MediaColumns.DATE_ADDED} desc")
        if (cursor != null) {
            //获取相册中所有的图片
//            while (cursor.moveToNext()) {
//                val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID))
//                val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
//                println("image uri is $uri")
//            }
            //这里只获取一张
            if (cursor.moveToNext()) {
                val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID))
                val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
                Log.w("-------", "image uri is $uri")

                //glide直接加载
                GlideApp.with(this).load(uri).into(iv_image)

                //也可以转成bitmap设置
//                val fd = contentResolver.openFileDescriptor(uri, "r")
//                if (fd != null) {
//                    val bitmap = BitmapFactory.decodeFileDescriptor(fd.fileDescriptor)
//                    fd.close()
//                    iv_image.setImageBitmap(bitmap)
//                }
            }
            cursor.close()
        }
    }

    //添加到图库
    fun addGallery(view: View) {
        thread {
            //不能直接写入外部储存，MediaStore写入
            val inputStream = GlideApp.with(this).asFile().load("https://i.keaitupian.net/up/05/51/8c/9eb1b9b9650cd9140a51fc51108c5105.jpg").submit().get().inputStream()
            writeInputStreamToAlbum(inputStream, "test_${System.currentTimeMillis()}.jpg", "image/jpg")
            Log.w("-------", "添加成功！")
        }
    }

    //添加到下载目录
    fun addDownload(view: View) {
        thread {
            //不能直接写入外部储存，MediaStore写入
            val inputStream = GlideApp.with(this).asFile().load("https://i.keaitupian.net/up/05/51/8c/9eb1b9b9650cd9140a51fc51108c5105.jpg").submit().get().inputStream()
            writeInputStreamToDownload(inputStream, "test.jpg")
            Log.w("-------", "添加成功！")
        }
    }

    private fun writeInputStreamToAlbum(inputStream: InputStream, displayName: String, mimeType: String) {

        val values = ContentValues()
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
        values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)//第二个参数写入哪个文件夹
        } else {
            values.put(MediaStore.MediaColumns.DATA, "${Environment.getExternalStorageDirectory().path}/${Environment.DIRECTORY_DCIM}/$displayName")
        }
        val bis = BufferedInputStream(inputStream)
        val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)//第一个参数,特定的uri
        if (uri != null) {
            val outputStream = contentResolver.openOutputStream(uri)
            if (outputStream != null) {
                val bos = BufferedOutputStream(outputStream)
                val buffer = ByteArray(1024)
                var bytes = bis.read(buffer)
                while (bytes >= 0) {
                    bos.write(buffer, 0, bytes)
                    bos.flush()
                    bytes = bis.read(buffer)
                }
                bos.close()
            }
        }
        bis.close()
    }


    private fun writeInputStreamToDownload(inputStream: InputStream, displayName: String) {
        val outputStream = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val values = ContentValues()
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_DOWNLOADS}/test")//第二个参数写入哪个文件夹
            val uri = contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)//第一个参数,特定的uri
            if (uri != null) {
                contentResolver.openOutputStream(uri)
            } else {
                null
            }
        } else {
            FileOutputStream(File("${Environment.getExternalStorageDirectory().path}/${Environment.DIRECTORY_DOWNLOADS}/test/$displayName"))
        }
        val bis = BufferedInputStream(inputStream)

        if (outputStream != null) {
            val bos = BufferedOutputStream(outputStream)
            val buffer = ByteArray(1024)
            var bytes = bis.read(buffer)
            while (bytes >= 0) {
                bos.write(buffer, 0, bytes)
                bos.flush()
                bytes = bis.read(buffer)
            }
            bos.close()
        }
        bis.close()
    }

    companion object {
        const val REQUEST_CODE_FOR_SINGLE_FILE = 100
        const val REQUEST_CODE_FOR_WRITE_FILE = 200
        const val REQUEST_CODE_FOR_DELETE_FILE = 300
    }


}